package org.gwc.controller;

import lombok.extern.slf4j.Slf4j;
import org.gwc.pojo.Schedule;
import org.gwc.service.ScheduleService;
import org.gwc.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@CrossOrigin // 允许其他源访问我们的controller 浏览器大哥就不拦截了
@RestController
@RequestMapping("schedule")
@Slf4j  // Slf4j接口，logback是实现
public class ScheduleController {

    @Autowired
    private ScheduleService scheduleService;

    // 该处函数只做两件事,1、接收参数 2、响应结果
    @GetMapping("/{pageSize}/{currentPage}")
    public R page(@PathVariable int pageSize,
                  @PathVariable int currentPage){
        R r = scheduleService.page(pageSize,currentPage);
        // 使用slf4j输出日志
        log.info("查询的数据为: {}",r);
        return r;
    }

    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable Integer id){
        R r = scheduleService.deleteById(id);
        return r;
    }

    // @RequestBody  代表接收请求体中的json数据,恰好json数据与Schedule匹配。可以用其接收
    // Schedule中的title和completed不能为空，可以在Schedule类本身中做校验
    // @Validateds使Schedule类本身的校验生效，BindingResult 校验结果
    @PostMapping
    public R insert(@Validated @RequestBody Schedule schedule, BindingResult result){
        if (result.hasErrors()){
            return R.fail("title or completed is null");
        }
        R r = scheduleService.insert(schedule);
        return r;

    }

    // 修改参数中，id，title,completed都不能为空
    // BindingResult只能校验title,completed不为空，id到Service层进行校验
    @PutMapping
    public R update(@Validated @RequestBody Schedule schedule, BindingResult result){
         if (result.hasErrors()){
             return R.fail("title or completed is null");
         }
         R r = scheduleService.update(schedule);
         return r;
    }
}
